package com.danger.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import com.danger.activity.KeepLiveActivity;

/**
 * Created by 俊 on 2018/4/28.
 */

public class KeepLiveService extends Service {

    private KeepLiveReceiver receiver;

    @Override
    public void onCreate() {
        super.onCreate();
        register();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (receiver == null) {
            register();
        }
        return START_STICKY;
    }

    private void register() {
        receiver = new KeepLiveReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(receiver, filter);
    }

    private class KeepLiveReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                Intent live_intent = new Intent(context, KeepLiveActivity.class);
                live_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(live_intent);
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                sendBroadcast(new Intent("finish"));
            }
        }
    }
}
